#include "sk_box_shape.h"
#include "sk_creation_params.h"

#include <QDomDocument>
#include <QDomElement>
#include <Box2D.h>

namespace sk
{

    BoxShape::BoxShape()
    {
    }

    int BoxShape::type()
    {
        return IT_SIMPLE_BOX;
    }

    GameShape * BoxShape::clone()
    {
        BoxShape * res = new BoxShape();
        res->bodyDef = bodyDef;
        res->fixtureDef = fixtureDef;
        res->w = w;
        res->h = h;
        return res;
    }

    b2Body * BoxShape::addToWorld(b2World * world)
    {

        b2BodyDef bd = bodyDef;
        bd.angle = bd.angle * DEGREES_TO_RAD;
        bd.position.Set(bd.position.x * PIXEL_TO_METERS, bd.position.y * PIXEL_TO_METERS);
        b2Body * body = world->CreateBody(&bd);

        b2PolygonShape s;

        b2Vec2 vertices[4];
        vertices[0].Set(0.0f, 0.0f);
        vertices[1].Set(w * PIXEL_TO_METERS, 0.0f);
        vertices[2].Set(w * PIXEL_TO_METERS, h * PIXEL_TO_METERS);
        vertices[3].Set(0.0f, h * PIXEL_TO_METERS);
        int32 count = 4;
        s.Set(vertices, count);

        fixtureDef.shape = &s;
        body->CreateFixture(&fixtureDef);
        return body;
    }


    void BoxShape::setData(void * params)
    {
        SimpleBoxParam * p = static_cast<SimpleBoxParam *>(params);
        w = p->w;
        h = p->h;
    }

    void BoxShape::serialiseCustomShapeData(QDomDocument * doc, QDomElement * e)
    {
        QDomElement customShapeElement = doc->createElement("customShapeData");
        customShapeElement.setAttribute("width", w);
        customShapeElement.setAttribute("height", h);
        e->appendChild(customShapeElement);
    }

    bool BoxShape::deserialiseCustomShapeData(QDomElement * e)
    {
        for (int i = 0; i < e->childNodes().count(); ++i)
        {
            QDomElement ee = e->childNodes().at(i).toElement();
            if (ee.tagName() == "customShapeData")
            {
                w = ee.attribute("width").toFloat();
                h = ee.attribute("height").toFloat();
                return true;
            }
        }
        return false;
    }

    QString BoxShape::xmlType()
    {
        return BoxShape::XmlType();
    }

    QString BoxShape::XmlType()
    {
        return "boxShape";
    }

} // namespace sk


